package com.yxd.processor;

import com.yxd.bootstrap.Constants;
import com.yxd.connector.http.HttpRequest;
import com.yxd.connector.http.HttpResponse;
import com.yxd.contract.HttpProcessor;
import com.yxd.util.ErrorPage;
import com.yxd.util.StrKit;

import java.io.*;

/**
 * Created by Administrator on 2016/6/15.
 */
public class StaticResourceProcessor extends HttpProcessor {

    @Override
    public void processor(HttpRequest request, HttpResponse response) {
        String uri = request.getRequestURI();
        if (StrKit.isWhiteSpaceOrNull(uri) || uri.equals("/")) {
            uri = "index.html";
        }
        File file = new File(Constants.WRB_ROOT, uri + Constants.SUBFIX);
        if (!file.exists()) {
            ErrorPage.error404(response);
        } else {
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                PrintWriter printWriter = response.getWriter();
                String line = bufferedReader.readLine();
                while (line != null && !line.equals("")) {
                    printWriter.print(line);
                    line = bufferedReader.readLine();
                }
                bufferedReader.close();
                printWriter.flush();
                printWriter.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
